local Networking = Tubes.Networking
local NetMessage = {}
NetMessage.__index = NetMessage

Networking.NetMessageDatastreamReader = Tubes.MakeConstructor (NetMessage)

datastream.Hook ("TDS", function (_, _, _, data)
	local Name = data [1]
	local Data = data [2]
	
	ErrorNoHalt ("Received datastream " .. Name .. "\n")
	Networking.Readers [Name] (Networking.NetMessageDatastreamReader (Data))
end)

function NetMessage:ctor (data)
	self.Data = data
	self.Index = 1
end

function NetMessage:BitField ()
	local Bits = {false, false, false, false, false, false, false, false}
	local UChar = self:UChar ()
	local Weight = 128
	for i = 1, 8 do
		if UChar >= Weight then
			Bits [9 - i] = true
			UChar = UChar - Weight
		end
		Weight = Weight / 2
	end
	return unpack (Bits)
end

function NetMessage:Char ()
	self.Index = self.Index + 1
	return self.Data [self.Index - 1]
end

NetMessage.Float = NetMessage.Char

function NetMessage:GetSource ()
	return "Server"
end

NetMessage.Long = NetMessage.Char

function NetMessage:Player ()
	return ents.GetByIndex (self:UChar ())
end

NetMessage.Short = NetMessage.Char
NetMessage.String = NetMessage.Char

function NetMessage:UChar ()
	self.Index = self.Index + 1
	return self.Data [self.Index - 1] + 128
end

function NetMessage:ULong ()
	self.Index = self.Index + 1
	return self.Data [self.Index - 1] + 2147483648
end

function NetMessage:UShort ()
	self.Index = self.Index + 1
	return self.Data [self.Index - 1] + 32768
end